package org.etnaframework.module.web.api;

import org.etnaframework.module.base.config.ConstantKeys;
import org.springframework.lang.NonNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HTTP请求及响应信息辅助工具类
 *
 * @author jasyaf
 * @since 2023-12-30
 */
public class WebCommonUtils {

    private WebCommonUtils() {
    }

    /**
     * 获取当前请求的Request对象
     */
    @NonNull
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes) {
            throw new IllegalStateException("Request is not found in current thread");
        }
        return requestAttributes.getRequest();
    }

    /**
     * 获取当前请求的Response对象
     */
    @NonNull
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == requestAttributes || null == requestAttributes.getResponse()) {
            throw new IllegalStateException("Response is not found in current thread");
        }
        return requestAttributes.getResponse();
    }

    /**
     * 自定义访问日志内容（例如模版渲染，日志记录模版名和参数，比直接记录渲染后的结果更直观）
     */
    public static void setCustomAccessLog(HttpServletRequest request, String customAccessLog) {
        request.setAttribute(ConstantKeys.CUSTOM_ACCESS_LOG, customAccessLog);
    }
}
